package com.shouhuobao.take.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.BaseActivityWithScroll;
import com.shouhuobao.take.model.BankBean;
import com.shouhuobao.take.utils.StringUtils;

import droid.frame.utils.Android;
import droid.frame.utils.android.MathUtils;

/**
 * Created by joker on 2017/8/8.
 * 提现界面
 */
public class TakeMoneyFromAccoutActivity extends BaseActivityWithScroll implements View.OnClickListener {

    private TextView mBindWXAccoutTV;//立即绑定微信账号或微信账号名称
    private TextView mCurrentReachMoneyTV;//实际到账的钱
    private EditText mTakeMoneyET;
    private LinearLayout mTotalMoneyLL;//可提现的金额布局
    private TextView mTotalMoneyTV;//可提现的金额显示
    private TextView mTakeSubmitTV;//提现按钮
    private TextView mOverTotalMoneyTipsTV;//超过总金额提示

    private String currentReachMoneyStr = "实际到账 ¥%1$s";
    private String totalMoneyStr = "可提现金额¥%1$s，";
    private String openId = "";
    private String nickName = "";
    private String totalMoney = "0";//总共金额
    private String takeMoney = "0";//提现的金额
    private int isBindWX = 0;//0未绑定 1已绑定

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setScrollHeight(100);
        showLoadingDialog(null);
        AppHttp.getInstance().queryTakeMoneyData();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_wallet_takemoneyfromaccout);
        super.findViewById();
        getAppTitle().setCommonTitle("提现");
        //设置标题右边显示
        findViewById(getResources().getIdentifier("title_right_switcher", "id", getPackageName())).setVisibility(View.VISIBLE);
        int right = getResources().getIdentifier("title_right_text", "id", getPackageName());
        TextView rightTV = (TextView) findViewById(right);
        rightTV.setText("提现记录");
        rightTV.setTextColor(getResources().getColor(R.color.app_font_green));
        rightTV.setOnClickListener(this);
        mBindWXAccoutTV = (TextView) findViewById(R.id.bindwxaccoutTV);
        mBindWXAccoutTV.setOnClickListener(this);
        mCurrentReachMoneyTV = (TextView) findViewById(R.id.current_reach_money_TV);
        mTakeMoneyET = (EditText) findViewById(R.id.money_ET);
        mTotalMoneyLL = (LinearLayout) findViewById(R.id.total_money_LL);
        mTotalMoneyTV = (TextView) findViewById(R.id.total_money_TV);
        findViewById(R.id.take_total_money_TV).setOnClickListener(this);
        mTakeSubmitTV = (TextView) findViewById(R.id.take_submit_TV);
        mTakeSubmitTV.setOnClickListener(this);
        mOverTotalMoneyTipsTV = (TextView) findViewById(R.id.over_total_money_tips_TV);
        mTakeSubmitTV.setEnabled(false);
        //设置输入框的hint
        SpannableString ss = new SpannableString("最小提现金额100元");//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(18, true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTakeMoneyET.setHint(new SpannedString(ss));

        mTakeMoneyET.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable s) {

                if (Double.parseDouble(totalMoney) < 100) {
                    mTakeSubmitTV.setEnabled(false);
                    return;
                }
                if (isNotEmpty(s)) {
                    if (StringUtils.isNumber(s.toString())) {
                        if (Double.parseDouble(s.toString()) <= Double.parseDouble(totalMoney)) {
                            mOverTotalMoneyTipsTV.setVisibility(View.GONE);
                            mTotalMoneyLL.setVisibility(View.VISIBLE);
                            if (Double.parseDouble(s.toString()) >= 100) {
                                mTakeSubmitTV.setEnabled(true);
                                takeMoney = (MathUtils.sub(s.toString(), 2)) + "";
                                mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, takeMoney));
                            } else {
                                mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                                mTakeSubmitTV.setEnabled(false);
                            }
                        } else {
                            mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                            mOverTotalMoneyTipsTV.setVisibility(View.VISIBLE);
                            mTotalMoneyLL.setVisibility(View.GONE);
                            mTakeSubmitTV.setEnabled(false);
                        }
                    } else {
                        mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                        mTakeSubmitTV.setEnabled(false);
                        showToast("输入的金额有误");
                    }
                } else {
                    mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                    mTotalMoneyLL.setVisibility(View.VISIBLE);
                    mOverTotalMoneyTipsTV.setVisibility(View.GONE);
                    mTakeSubmitTV.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //提现记录
            case R.id.title_right_text:
                intent = new Intent(getContext(), TakeMoneyHistoryActivity.class);
                intent.putExtra("isFrom", 0);
                startActivity(intent);
                break;
            //全部提现
            case R.id.take_total_money_TV:
                if (Double.parseDouble(totalMoney) == 0) {
                    mTakeSubmitTV.setEnabled(false);
                    return;
                }
                if (Double.parseDouble(totalMoney) < 100) {
                    mTakeSubmitTV.setEnabled(false);
                    showToast("可提现金额最低为100元");
                    return;
                }
                mTakeMoneyET.setText(totalMoney);
                mTakeMoneyET.setSelection(totalMoney.length());
                takeMoney = (MathUtils.sub(totalMoney, 2)) + "";
                mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, takeMoney));
                break;
            //提现
            case R.id.take_submit_TV:
                if (isBindWX == 1) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().takeMoneyFromBank(mTakeMoneyET.getText().toString().trim());
                } else {
                    showToast("请绑定微信账号");
                }
                break;
            //未绑定微信账号，点击跳转到绑定微信页面
            case R.id.bindwxaccoutTV:
                if (isBindWX == 0) {
                    intent = new Intent(getContext(), BindWXAccoutActivity.class);
                    intent.putExtra("isFrom", 1);
                    startActivityForResult(intent, 101);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Android.toggleSoftInput(getContext());
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.query_take_money_data:
                cancelLoadingDialog();
                final ReqResult<BankBean> reqResult = JSON.parser(msg.obj, BankBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(reqResult)) {
                            BankBean bean = reqResult.getResult();
                            if (isNotEmpty(bean.getOpenId())) {//已经绑定
                                isBindWX = 1;
                                nickName = bean.getWxName();
                                openId = bean.getOpenId();
                                mBindWXAccoutTV.setText(nickName);
                                mBindWXAccoutTV.setTextColor(getResources().getColor(R.color.app_font));
                            } else {//未绑定
                                isBindWX = 0;
                                mBindWXAccoutTV.setText("立即绑定微信账号");
                                mBindWXAccoutTV.setTextColor(getResources().getColor(R.color.app_font_green));
                            }
                            totalMoney = bean.getAccountBalance();
                            mTotalMoneyLL.setVisibility(View.VISIBLE);
                            mTotalMoneyTV.setText(String.format(totalMoneyStr, bean.getAccountBalance()));
                        } else {
                            showToast(reqResult.getMessage());
                        }
                    }
                });
                return true;
            case MsgID.take_money_data:
                cancelLoadingDialog();
                final ReqResult<?> result = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result)) {
                            //提现成功后跳转到提现记录界面
                            Intent intent = new Intent(getContext(), TakeMoneyHistoryActivity.class);
                            intent.putExtra("isFrom", 1);
                            startActivityForResult(intent, 102);
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 101) {
            nickName = data.getStringExtra("nickname");
            openId = data.getStringExtra("openId");
            if (isNotEmpty(openId)) {
                isBindWX = 1;
                mBindWXAccoutTV.setText(nickName);
                mBindWXAccoutTV.setTextColor(getResources().getColor(R.color.app_font));
            } else {
                isBindWX = 0;
                mBindWXAccoutTV.setText("立即绑定微信账号");
                mBindWXAccoutTV.setTextColor(getResources().getColor(R.color.app_font_green));
            }
        } else if (requestCode == 102) {//刷新提现界面数据
            showLoadingDialog(null);
            String money = "";
            mTakeMoneyET.setText(money);
            takeMoney = "0";
            mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, takeMoney));
            AppHttp.getInstance().queryTakeMoneyData();
        }
    }


}
